// 外卖平台数据库系统
// 使用 localStorage 模拟数据库功能

class Database {
    constructor() {
        this.initDatabase();
    }

    // 初始化数据库
    initDatabase() {
    // 初始化用户数据
        if (!localStorage.getItem('users')) {
            const users = [
            {
                id: 1,
                    username: 'admin',
                    password: '1234',
                    phone: '13800138000',
                    email: 'admin@test.com',
                    type: 'user',
                    name: '管理员',
                    avatar: '👤',
                    registerTime: new Date().toLocaleString()
            },
            {
                id: 2,
                    username: 'merchant1',
                    password: '1234',
                    phone: '13800138001',
                    email: 'merchant@test.com',
                    type: 'merchant',
                    name: '美味餐厅',
                    avatar: '🏪',
                    registerTime: new Date().toLocaleString(),
                    restaurantInfo: {
                        name: '美味餐厅',
                        address: '北京市朝阳区xxx街道123号',
                phone: '010-12345678',
                        description: '正宗川菜，麻辣鲜香',
                rating: 4.8,
                        deliveryTime: '30分钟',
                deliveryFee: 5,
                        minOrder: 20
                    }
            },
            {
                id: 3,
                    username: 'rider1',
                    password: '1234',
                    phone: '13800138002',
                    email: 'rider@test.com',
                    type: 'rider',
                    name: '张师傅',
                    avatar: '🏍️',
                    registerTime: new Date().toLocaleString(),
                    riderInfo: {
                        vehicle: '电动车',
                        license: 'A123456',
                        area: '朝阳区',
                rating: 4.9,
                        completedOrders: 156
                    }
                }
            ];
            localStorage.setItem('users', JSON.stringify(users));
    }

    // 初始化菜品数据
        if (!localStorage.getItem('dishes')) {
            const dishes = [
            {
                id: 1,
                    merchantId: 2,
                name: '宫保鸡丁',
                price: 28,
                originalPrice: 32,
                    category: '川菜',
                    description: '经典川菜，鸡肉嫩滑，花生香脆，麻辣鲜香',
                    image: 'https://images.unsplash.com/photo-1563379091339-03246963d4d2?w=400&h=300&fit=crop',
                stock: 50,
                cookingTime: 15,
                    tags: ['辣', '推荐', '热销'],
                    ingredients: '鸡肉,花生,干辣椒,花椒,葱,姜,蒜',
                    allergens: '花生',
                    rating: 4.7,
                    sales: 128,
                    createTime: new Date().toLocaleString()
            },
            {
                id: 2,
                    merchantId: 2,
                name: '麻婆豆腐',
                    price: 22,
                    originalPrice: 26,
                    category: '川菜',
                    description: '嫩滑豆腐配麻辣调料，口感丰富',
                    image: 'https://images.unsplash.com/photo-1582878826629-29b7ad1cdc43?w=400&h=300&fit=crop',
                stock: 30,
                    cookingTime: 12,
                    tags: ['辣', '素食'],
                    ingredients: '豆腐,猪肉末,豆瓣酱,花椒,葱,姜',
                    allergens: '大豆',
                    rating: 4.5,
                    sales: 89,
                    createTime: new Date().toLocaleString()
            },
            {
                id: 3,
                    merchantId: 2,
                name: '回锅肉',
                    price: 35,
                    originalPrice: 40,
                    category: '川菜',
                    description: '肥瘦相间的五花肉，配青椒炒制',
                    image: 'https://images.unsplash.com/photo-1565299624946-b28f40a0ca4b?w=400&h=300&fit=crop',
                stock: 25,
                    cookingTime: 18,
                    tags: ['辣', '推荐'],
                    ingredients: '五花肉,青椒,豆瓣酱,甜面酱,葱,姜,蒜',
                    allergens: '无',
                    rating: 4.6,
                    sales: 76,
                    createTime: new Date().toLocaleString()
                },
            {
                id: 4,
                merchantId: 2,
                    name: '水煮鱼',
                    price: 48,
                    originalPrice: 55,
                    category: '川菜',
                    description: '鲜嫩鱼肉，麻辣汤底，配菜丰富',
                    image: 'https://images.unsplash.com/photo-1563379091339-03246963d4d2?w=400&h=300&fit=crop',
                    stock: 20,
                    cookingTime: 25,
                    tags: ['辣', '热销'],
                    ingredients: '草鱼,豆芽,白菜,干辣椒,花椒,葱,姜',
                    allergens: '鱼类',
                    rating: 4.8,
                    sales: 95,
                    createTime: new Date().toLocaleString()
            },
            {
                id: 5,
                merchantId: 2,
                    name: '蒜蓉西兰花',
                    price: 18,
                    originalPrice: 20,
                    category: '素菜',
                    description: '清爽素菜，蒜香浓郁，营养丰富',
                    image: 'https://images.unsplash.com/photo-1512621776951-a57141f2eefd?w=400&h=300&fit=crop',
                    stock: 40,
                    cookingTime: 8,
                    tags: ['素食', '健康'],
                    ingredients: '西兰花,大蒜,盐,鸡精',
                    allergens: '无',
                    rating: 4.3,
                    sales: 45,
                    createTime: new Date().toLocaleString()
                },
            {
                id: 6,
                    merchantId: 2,
                    name: '蛋炒饭',
                    price: 15,
                    originalPrice: 18,
                    category: '主食',
                    description: '粒粒分明的米饭，配鸡蛋炒制',
                    image: 'https://images.unsplash.com/photo-1603133872878-684f208fb84b?w=400&h=300&fit=crop',
                    stock: 60,
                    cookingTime: 10,
                    tags: ['推荐', '经济'],
                    ingredients: '米饭,鸡蛋,葱花,盐,生抽',
                    allergens: '鸡蛋',
                    rating: 4.4,
                    sales: 112,
                    createTime: new Date().toLocaleString()
                }
            ];
            localStorage.setItem('dishes', JSON.stringify(dishes));
    }

    // 初始化订单数据
        if (!localStorage.getItem('orders')) {
            const orders = [
            {
                    id: 1001,
                userId: 1,
                    merchantId: 2,
                riderId: null,
                    dishes: [
                        { id: 1, name: '宫保鸡丁', price: 28, quantity: 1 },
                        { id: 6, name: '蛋炒饭', price: 15, quantity: 1 }
                    ],
                    totalPrice: 43,
                    deliveryFee: 5,
                    finalPrice: 48,
                status: 'pending',
                    riderStatus: 'available',
                    orderTime: new Date().toLocaleString(),
                    deliveryAddress: '北京市朝阳区xxx小区1号楼2单元301',
                    customerPhone: '13800138000',
                customerName: '张三',
                    notes: '请送到门口',
                    estimatedTime: 30
                },
                {
                    id: 1002,
                    userId: 1,
                merchantId: 2,
                    riderId: 3,
                    dishes: [
                        { id: 2, name: '麻婆豆腐', price: 22, quantity: 1 },
                        { id: 5, name: '蒜蓉西兰花', price: 18, quantity: 1 }
                    ],
                    totalPrice: 40,
                    deliveryFee: 5,
                    finalPrice: 45,
                    status: 'delivering',
                    riderStatus: 'delivering',
                    orderTime: new Date(Date.now() - 15 * 60000).toLocaleString(),
                    deliveryAddress: '北京市朝阳区xxx小区2号楼1单元201',
                    customerPhone: '13800138000',
                customerName: '李四',
                    notes: '请敲门',
                    estimatedTime: 25,
                    riderName: '张师傅'
                }
            ];
            localStorage.setItem('orders', JSON.stringify(orders));
        }

        // 初始化商家数据
        if (!localStorage.getItem('merchants')) {
            const merchants = [
            {
                id: 2,
                    name: '美味餐厅',
                    type: '川菜',
                    address: '北京市朝阳区xxx街道123号',
                    phone: '010-12345678',
                    description: '正宗川菜，麻辣鲜香，传承经典',
                    image: 'https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?w=400&h=300&fit=crop',
                    rating: 4.8,
                    deliveryTime: '30分钟',
                    deliveryFee: 5,
                    minOrder: 20,
                    openTime: '09:00-22:00',
                    isOpen: true,
                    tags: ['川菜', '麻辣', '正宗'],
                    sales: 1256,
                    createTime: new Date().toLocaleString()
                }
            ];
            localStorage.setItem('merchants', JSON.stringify(merchants));
        }
    }

    // 用户相关操作
    getUsers() {
        return JSON.parse(localStorage.getItem('users') || '[]');
    }

    getUserById(id) {
        const users = this.getUsers();
        return users.find(user => user.id === id);
    }

    getUserByUsername(username) {
        const users = this.getUsers();
        return users.find(user => user.username === username);
    }

    addUser(user) {
        const users = this.getUsers();
        user.id = this.getNextId(users);
        user.registerTime = new Date().toLocaleString();
        users.push(user);
        localStorage.setItem('users', JSON.stringify(users));
        return user;
    }

    updateUser(id, updates) {
        const users = this.getUsers();
        const index = users.findIndex(user => user.id === id);
        if (index !== -1) {
            users[index] = { ...users[index], ...updates };
            localStorage.setItem('users', JSON.stringify(users));
            return users[index];
        }
        return null;
    }

    // 菜品相关操作
    getDishes() {
        return JSON.parse(localStorage.getItem('dishes') || '[]');
    }

    getDishesByMerchant(merchantId) {
        const dishes = this.getDishes();
        return dishes.filter(dish => dish.merchantId === merchantId);
    }

    getDishById(id) {
        const dishes = this.getDishes();
        return dishes.find(dish => dish.id === id);
    }

    addDish(dish) {
        const dishes = this.getDishes();
        dish.id = this.getNextId(dishes);
        dish.createTime = new Date().toLocaleString();
        dishes.push(dish);
        localStorage.setItem('dishes', JSON.stringify(dishes));
        return dish;
    }

    updateDish(id, updates) {
        const dishes = this.getDishes();
        const index = dishes.findIndex(dish => dish.id === id);
        if (index !== -1) {
            dishes[index] = { ...dishes[index], ...updates };
            localStorage.setItem('dishes', JSON.stringify(dishes));
            return dishes[index];
        }
        return null;
    }

    deleteDish(id) {
        const dishes = this.getDishes();
        const filteredDishes = dishes.filter(dish => dish.id !== id);
        localStorage.setItem('dishes', JSON.stringify(filteredDishes));
        return true;
    }

    // 订单相关操作
    getOrders() {
        return JSON.parse(localStorage.getItem('orders') || '[]');
    }

    getOrdersByUser(userId) {
        const orders = this.getOrders();
        return orders.filter(order => order.userId === userId);
    }

    getOrdersByMerchant(merchantId) {
        const orders = this.getOrders();
        return orders.filter(order => order.merchantId === merchantId);
    }

    getOrdersByRider(riderId) {
        const orders = this.getOrders();
        return orders.filter(order => order.riderId === riderId);
    }

    getAvailableOrders() {
        const orders = this.getOrders();
        return orders.filter(order => order.riderStatus === 'available');
    }

    getOrderById(id) {
        const orders = this.getOrders();
        return orders.find(order => order.id === id);
    }

    addOrder(order) {
        const orders = this.getOrders();
        order.id = this.getNextId(orders);
        order.orderTime = new Date().toLocaleString();
        order.status = 'pending';
        order.riderStatus = 'available';
        orders.push(order);
        localStorage.setItem('orders', JSON.stringify(orders));
        return order;
    }

    updateOrder(id, updates) {
        const orders = this.getOrders();
        const index = orders.findIndex(order => order.id === id);
        if (index !== -1) {
            orders[index] = { ...orders[index], ...updates };
            localStorage.setItem('orders', JSON.stringify(orders));
            return orders[index];
        }
        return null;
    }

    // 商家相关操作
    getMerchants() {
        return JSON.parse(localStorage.getItem('merchants') || '[]');
    }

    getMerchantById(id) {
        const merchants = this.getMerchants();
        return merchants.find(merchant => merchant.id === id);
    }

    // 工具方法
    getNextId(items) {
        if (items.length === 0) return 1;
        return Math.max(...items.map(item => item.id)) + 1;
    }

    // 位置追踪相关操作
    getRiderLocations() {
        return JSON.parse(localStorage.getItem('riderLocations') || '[]');
    }

    getRiderLocationById(riderId) {
        const locations = this.getRiderLocations();
        const riderLocations = locations.filter(loc => loc.riderId === riderId);
        return riderLocations.length > 0 ? riderLocations[riderLocations.length - 1] : null;
    }

    addRiderLocation(locationData) {
        const locations = this.getRiderLocations();
        locations.push({
            ...locationData,
            id: this.getNextId(locations),
            timestamp: new Date().toISOString()
        });
        
        // 只保留最近100条记录
        if (locations.length > 100) {
            locations.splice(0, locations.length - 100);
        }
        
        localStorage.setItem('riderLocations', JSON.stringify(locations));
        return locationData;
    }

    getActiveRiderLocations() {
        const locations = this.getRiderLocations();
        const now = new Date();
        const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);
        
        return locations.filter(loc => {
            const locationTime = new Date(loc.timestamp);
            return locationTime > fiveMinutesAgo;
        });
    }

    // 清空所有数据
    clearAllData() {
        localStorage.removeItem('users');
        localStorage.removeItem('dishes');
        localStorage.removeItem('orders');
        localStorage.removeItem('merchants');
        localStorage.removeItem('riderLocations');
        localStorage.removeItem('currentUser');
        this.initDatabase();
    }

    // 导出数据
    exportData() {
        return {
            users: this.getUsers(),
            dishes: this.getDishes(),
            orders: this.getOrders(),
            merchants: this.getMerchants()
        };
    }

    // 导入数据
    importData(data) {
        if (data.users) localStorage.setItem('users', JSON.stringify(data.users));
        if (data.dishes) localStorage.setItem('dishes', JSON.stringify(data.dishes));
        if (data.orders) localStorage.setItem('orders', JSON.stringify(data.orders));
        if (data.merchants) localStorage.setItem('merchants', JSON.stringify(data.merchants));
    }
}

// 创建全局数据库实例
window.db = new Database();

// 导出数据库类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = Database;
}